﻿using System;
using System.Collections.Generic;
using System.Text;

namespace WowGuildSite.Armory
{
    public class ArmoryItemHarvester
    {
        public delegate void ProgressDelegate(double percentage, int currentIndex );
        public delegate void HarvestDelegate( ArmoryItem item,ArmoryAccessor accessor );

        private ArmoryAccessor accessor;

        public void Perform( int start,int end,ProgressDelegate progressCallback,HarvestDelegate harvestCallback )
        {
            if ( start < 0 )
            {
                throw new ArgumentException("Start index must be positive.","start");
            }
            if ( end < start )
            {
                throw new ArgumentException("End index must be larger than start index.","end");
            }

            double lastPercentage = 0.0;
            bool first = true;

            for( int i = start; i <= end; i++ )
            {
                if ( accessor.ExistsItem(i) )
                {
                    ArmoryItem item = accessor.GetItem(i);

                    if ( item != null )
                    {
                        if ( harvestCallback != null )
                        {
                            harvestCallback(item, accessor);
                        }
                    }

                    // Calculate percentage:
                    double percentage = (double) i/((double) end - (double) start);
                    percentage *= 100.0;

                    if ( percentage - 1.0 > lastPercentage || first )
                    {
                        if ( progressCallback != null )
                        {
                            progressCallback(percentage, i);
                        }

                        lastPercentage = percentage;
                        first = false;
                    }
                }
            }
        }

        public ArmoryItemHarvester( ArmoryAccessor accessor )
        {
            if ( accessor == null )
            {
                throw new ArgumentNullException("accessor");
            }
            this.accessor = accessor;
        }
    }
}
